package com.edan.partnerback.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.edan.partnerback.common.Constants;
import com.edan.partnerback.common.VO.Result;
import com.edan.partnerback.common.annotation.AutoLog;
import com.edan.partnerback.exception.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Description 功能描述
 * @Author Edan
 * @Create 2024/3/30 17:56
 */
@Api(tags = "文件下载上传接口")
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {
    @Value("${file.upload.path:}")
    private String uploadPath;
    @Value("${file.download.ip:localhost}")
    private String download;
    @Value("${server.port}")
    private String serverPort;

    @ApiOperation(value = "文件上传接口")
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {

        String originalFilename = file.getOriginalFilename();  //文件全名
        String mainName = FileUtil.mainName(originalFilename); // 文件主名称
        String extName = FileUtil.extName(originalFilename); //文件后缀名
        //返回的文件读取路径
        String downloadPath = IdUtil.fastSimpleUUID() + StrUtil.DOT + extName;
        //本地的文件路径
        String localPath = getLocalFileName(downloadPath);

        try {
            File uploadFile = new File(localPath);
            File parentFile = uploadFile.getParentFile();
            if (!parentFile.exists()) { //检查上级目录是否存在
                parentFile.mkdirs();
            }
            //文件移动，将上传的文件内容传输到目标文件中
            file.transferTo(uploadFile);

        } catch (Exception e) {
            log.error("文件上传失败", e);
            return Result.error("文件上传失败");
        }
        return Result.success("http://" + download + StrUtil.COLON + serverPort + "/file/download/" + downloadPath);
    }

    /**
     * 如果需要进行下载用户限定可以手动校验token，或者携带token即可
     * @param downloadPath
     * @param response
     * @throws IOException
     */
    @AutoLog("文件下载")
    @ApiOperation(value = "全局文件下载，无需token")
    @GetMapping("/download/{downloadPath}")
    public void downloadFile(@PathVariable String downloadPath,
                             // @RequestParam String
                             // @RequestParam(required = false) String token,
                             HttpServletResponse response) throws IOException {

        String localFileName = getLocalFileName(downloadPath);
        File localFile = new File(localFileName);
        if (FileUtil.isEmpty(localFile)) {
            throw new ServiceException("文件不存在或文件为空");
        }
        byte[] bytes = FileUtil.readBytes(localFile);

        try (ServletOutputStream stream = response.getOutputStream()) {
            String extName = FileUtil.extName(downloadPath);
            response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(downloadPath, "UTF-8"));//在线预览
            //可抽取出来
            List<String> attachmentFileExtNames = CollUtil.newArrayList("docx", "doc", "xlsx", "xls", ",map4", "map3");
            if (attachmentFileExtNames.contains(extName)) {
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(downloadPath, "UTF-8"));//附件下载
            }

            stream.write(bytes);
            // stream.flush();
        }

        // return Result.success(bytes);

    }

    private String getLocalFileName(String downloadPath) {
        if (StrUtil.isBlank(uploadPath)) {
            uploadPath = System.getProperty("user.dir");
        }
        //拼接成本地地址
        return uploadPath + Constants.FILE_DIR + downloadPath;
    }
}
